"use client";
import { useEffect, useState } from "react";
import { LoginBox } from "./globals";
import { Button, Card, Checkbox, Form, FormProps, Input, message } from "antd";
import { IUser } from "@/type/user";
import { LoginApi } from "./api";
import { useRouter } from "next/navigation";

type FieldType = {
  username: string;
  password: string;
  remember?: string;
};

export default function Home() {
  const router = useRouter();



  const [data, setData] = useState<IUser[]>([]);
  const [windowWidth, setWindowWidth] = useState(0);
  const [messageApi, contextHolder] = message.useMessage();

  useEffect(() => {
    if (typeof window !== "undefined") {
      setWindowWidth(window.innerWidth);

      const handleResize = () => {
        setWindowWidth(window.innerWidth);
      };

      window.addEventListener("resize", handleResize);
    }
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch("/api/getData");
      console.log("Response: ", response);
      const res = await response.json();
      const data = res.data as IUser[];
      setData(data);
      console.log("data: ", data);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };
  // 修改用户数据
  const handleChangeUserData = async () => {
    try {
      const response = await fetch("/api/user/user-add", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          newName: "NewUserName",
          newAge: 25,
          newDepartmentId: 1,
        }), // 示例数据
      });
      const res = await response.json();
      console.log("Change User Name Response: ", res);
      // 重新获取数据以反映更改
      fetchData();
    } catch (error) {
      console.error("Error changing user name:", error);
    }
  };

  // 登录完成
  const onFinish: FormProps<FieldType>["onFinish"] = async (values) => {
    const { code, msg } = (await LoginApi({
      username: values.username,
      password: values.password,
    })) as { code: number; msg: string };
    console.log(code)
    if (code === 200) {
      messageApi.open({
        type: "success",
        content: msg,
        duration: 2,
      });
      // Dismiss manually and asynchronously
      setTimeout(messageApi.destroy, 2500);
      router.push('/admin/officeManagement/workLog')

    } else {
      messageApi.open({
        type: "error",
        content: msg,
        duration: 2,
      });
    }
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <LoginBox>
      {data.map((item: IUser) => (
        <div key={item.id}>
          <h2>{item.name}</h2>
          <p>Age: {item.age}</p>
          <Button onClick={() => handleChangeUserData()}>Fetch Data</Button>
        </div>
      ))}
      <Card
        title="NEXT LOGIN"
        // extra={<a href="#">More</a>}
        style={{ width: 400 }}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="Username"
            name="username"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="Password"
            name="password"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item<FieldType>
            name="remember"
            valuePropName="checked"
            label={null}
          >
            <Checkbox>记住密码</Checkbox>
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>

            {contextHolder}
    </LoginBox>
  );
}
